/*
 * EarthdawnNetApp.java
 */
package earthdawnnet.client;

import earthdawnnet.events.client.IClientEventHandler;
import earthdawnnet.util.Chat;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * The main class of the application.
 */
public class EarthdawnNetApp extends SingleFrameApplication implements IClientEventHandler
{
    private Client client;
    private Chat chat;
    private EarthdawnNetView view;
    /**
     * At startup create and show the main frame of the application.
     */
    @Override
    protected void startup()
    {
        chat = new Chat();
        client = new Client(chat, this);
        view = new EarthdawnNetView(this, client);
        chat.addObserver(view);
        show(view);
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     */
    @Override
    protected void configureWindow(java.awt.Window root)
    {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of EarthdawnNetApp
     */
    public static EarthdawnNetApp getApplication()
    {
        return Application.getInstance(EarthdawnNetApp.class);
    }

    @Override
    public void shutdown()
    {
        if(client != null) client.saveNExit();
        super.shutdown();
    }

    /**
     * Main method launching the application.
     */
    public static void main(String[] args)
    {
        launch(EarthdawnNetApp.class, args);
    }

    public void addLine(String line)
    {
        chat.add(line);
    }
    
    AtomicReferenceArray<String> viewers;
    AtomicIntegerArray viewerIDs;
    
    public int getId(int i)
    {
        return viewerIDs.get(i);
    }

    public void clientsChanged(String[] names, int[] ids)
    {
        viewers = new AtomicReferenceArray<String>(names);
        viewerIDs = new AtomicIntegerArray(ids);
        view.setViewerNames(names);
    }

    public void serverShutdown()
    {
        client.close();
        view.updateConnectionText();
    }

    void connectionClosed()
    {
        view.updateConnectionText();
    }

    public void loggedIn(Collection<String> chatLines)
    {
        //System.out.println("Logged in. Existing chat lines: " + chatLines.size());
        chat.addAll(chatLines);
    }

    public void kicked()
    {
        client.close();
        view.updateConnectionText();
    }
}
